/**
 * Project  : Looker
 * Package  : net.freestu.looker.monitor
 * File     : LinkExtractor.java
 * Author   : solosky < solosky772@qq.com >
 * Date     : Aug 23, 2009
 * Modified : Aug 23, 2009
 * License  : Apache License 2.0 
 */
package net.freestu.looker.monitor;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import net.freestu.looker.common.Media;
import net.freestu.looker.common.NewsEntity;
import net.freestu.looker.util.URLUtils;

/**
 *  提取正文中的链接
 */
public class LinkExtractor extends AbstractExtractor
{

	/**
	 * 构造函数
     * @param newsEntity
     */
    public LinkExtractor(NewsEntity newsEntity)
    {
	    super(newsEntity);
    }

	/* (non-Javadoc)
     * @see net.freestu.looker.monitor.AbstractExtractor#extract()
     */
    @Override
    public void extract()
    {
    	//解析出连接
		String regxp = "<a.*?href=['\"](.*?)['\"].*?>(.*?)</a>";
		Media media = null;
		String content = newsEntity.getContent();
		Pattern pt = Pattern.compile(regxp,Pattern.CASE_INSENSITIVE);	//不区分大小写
		Matcher mc = pt.matcher(content);
		while (mc.find()){
			
			String relUrl = mc.group(1);
			String absUrl = URLUtils.real(mc.group(1), newsEntity.getUrl());
			media = new Media();
			media.setUrl(absUrl);
			media.setNewsEntity(newsEntity);
			media.setDate(new Date());
			newsEntity.getMediaList().add(media);
			
			//这里还需要做一个工作就是把相对路径替换为绝对路径
			//比如:<a href="./good/job.html">工作</a>   应替换为 <a href="http://www.cd.com/good/job.html">工作</a>
			if(!relUrl.startsWith("http://")){
				content = content.replace(relUrl,absUrl);
			}
			logger.debug("成功解析链接:"+mc.group(1));
		}
		newsEntity.setContent(content);
    }
    
    

}
